package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.common.PostDubbleEvent;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.common.QueryUserUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.OmsDlOnlineStockCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * 线上订单占用
 * @author kangcong
 * @date 2018/09/29
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class OmsDlOnlineStockCmdImpl extends CommandAdapter implements OmsDlOnlineStockCmd {

    @Autowired
    QueryCpUtil queryCpUtil;

    @Autowired
    private QueryUserUtil queryUserUtil;

    @Autowired
    PostDubbleEvent postDubbleEvent;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

//        log.debug("-----------线上订单占用----------" + map);
        log.info("OmsDlOnlineStockCmdImpl--map-->{}",map);

        ValueHolder vh = new ValueHolder();
        JSONArray retArray = new JSONArray();
        JSONObject data = null;

        try {
            String param = map.get("param").toString();
            data = JSON.parseObject(param);
            if (null == data || data.size() == 0) {
                throw new NDSException("data is null!");
            }
        } catch (Exception e) {
            vh.put("code", -1);
            vh.put("message", "参数转换异常:" + map.toString());

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            if ((e instanceof NDSException)) {
                throw e;
            } else {
                throw new NDSException(sw.toString());
            }

        }
        if (vh.getData().size() > 0) {
            return vh;
        }

        if (null == data || (!data.containsKey("PS_C_ORDER_OCCUPY"))) {
            throw new NDSException("参数格式错误！" + map);
        }

        JSONArray dataArray = data.getJSONArray("PS_C_ORDER_OCCUPY");

        try {
            //调用标服
            String userName = "INTER99999";
            User user = queryUserUtil.getUser(userName);
            QuerySessionImpl querySession = new QuerySessionImpl(user);
            String noticSave = "com.jackrain.nea.dl.eco.api.DlOnLineStockCmd:1.0:dl";

            for (int i = 0; i < dataArray.size(); i++) {
                
                JSONObject oldzb = dataArray.getJSONObject(i);
                Long id = oldzb.getLong("ID");
                JSONObject fixcolumn = new JSONObject();
                JSONObject retInfo = new JSONObject();
                fixcolumn.put("DL_B_ONLINESTOCK", oldzb);

                HashMap fixcolumn1 = new HashMap();
                fixcolumn1.put("param", fixcolumn);

                DefaultWebEvent event = new DefaultWebEvent("dlbonlinestock", new HashMap(16));
                event.put("param", fixcolumn1);
                querySession.setEvent(event);
//                log.debug("------------线上订单占用=" + fixcolumn1);
                accesLogger.info("OmsDlOnlineStockCmdImpl--fixcolumn1-->{}",fixcolumn1);

                JSONObject retSaveJo = null;
                try {
                    retSaveJo = postDubbleEvent.executePostDubbleToMap(noticSave, querySession);
                    accesLogger.info("OmsDlOnlineStockCmdImpl--retSaveJo-->{}",retSaveJo);
                } catch (Exception e) {
                    retInfo.put("ID",id);
                    retInfo.put("code",-1);
                    retInfo.put("message",e);
                    log.error("OmsDlOnlineStockCmdImpl-dubboerror--->{}"+e);
                }
//                log.debug("retSaveJo" + retSaveJo);

                if (retSaveJo == null) {
                    retInfo.put("code", -1);
                    retInfo.put("message", "调用线上订单占用失败，调用标服返回为空");
                    retInfo.put("ID",id);
                    retArray.add(retInfo);
                    continue;
                }
                if (retSaveJo.containsKey("code") && (int) retSaveJo.get("code") != 0) {
                    if (null == retSaveJo.get("message")) {
                        retInfo.put("message", "调用失败，调用标服返回为空");
                    } else {
                        retInfo.put("message", "调用失败，->" + retSaveJo.get("message"));
                    }
                    retInfo.put("code", -1);
                    retInfo.put("ID",id);
                    retArray.add(retInfo);
                    continue;
                }
            }

            vh.put("code", 0);
            vh.put("message", "success");


        } catch (Exception e) {
            vh.put("code", -1);
            vh.put("message", "调用线上订单占用失败" + e);

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
//            if ((e instanceof NDSException)) {
//                throw e;
//            } else {
//                throw new NDSException(sw.toString());
//            }
        }
        vh.put("retStr", retArray);
        return vh;
    }
}
